package user

import (
	"context"
	"gitee.com/zyw0605688_admin/gozero/user/model"
	"github.com/duke-git/lancet/v2/cryptor"
	"github.com/golang-jwt/jwt/v5"
	"time"

	"gitee.com/zyw0605688_admin/gozero/user/internal/svc"
	"gitee.com/zyw0605688_admin/gozero/user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.UserLoginResponse, err error) {
	// 拿到前端传过来的参数
	// 从数据库里找，比对上，就可以登录
	item := model.User{}
	err = l.svcCtx.DB.Where("username = ? and password = ?", req.UserName, cryptor.Md5String(req.Password)).First(&item).Error
	if err != nil {
		logx.Error("查询数据库报错")
		return nil, err
	}
	AccessSecret := l.svcCtx.Config.Auth.AccessSecret
	token, err := genToken(item.Id, item.UserName, item.Email, AccessSecret)
	if err != nil {
		logx.Error("生成token失败")
		return nil, err
	}
	resp = &types.UserLoginResponse{
		UserName:  item.UserName,
		Password:  item.Password,
		Id:        item.Id,
		Email:     item.Email,
		CreatedAt: item.CreatedAt,
		Token:     token,
	}
	return
}

func genToken(id, username, email, AccessSecret string) (resp string, err error) {
	JwtSigningKey := []byte(AccessSecret)
	type MyCustomClaims struct {
		Id       string `json:"id"`
		UserName string `json:"username"`
		Email    string `json:"email"`
		jwt.RegisteredClaims
	}

	claims := MyCustomClaims{
		id, username, email,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	resp, err = token.SignedString(JwtSigningKey)
	return resp, err
}
